#include <iostream>
#include <cstring>
#include <stdexcept>
#include <string>
#include <streambuf>

#include "Shader.h"
#include "exceptions.h"

using namespace std;

Shader::Shader(GLenum type, string path) {
	this->type = type;
	name = path;

	file.open(path.c_str(), ios::in);
	string line;
	while(!file.eof()) {
		getline(file, line);
		programSource += line;
	}
	file.close();
}

void Shader::compile() {
	if(glIsShader(handle) == GL_TRUE) {
		glDeleteShader(handle);
	}
	//cout << "Compiling shader " << name << endl;
	handle = glCreateShader(type);
	const char* src = programSource.c_str();
	glShaderSource(handle, 1, &src, NULL);
	glCompileShader(handle);

	// Check to see if the shader compiled successfully
	int compiled;
	glGetShaderiv(handle, GL_COMPILE_STATUS, &compiled);

	if (compiled != GL_TRUE) {
		int length;
		glGetShaderiv(handle, GL_INFO_LOG_LENGTH, &length);
		char log[1024];
		glGetShaderInfoLog(handle, length, &length, log);
		throw GameException("Failed to compile " + name + "\n" + log + "\n");
	}
}

Shader::~Shader() {
	//cout << "Deleting shader " << name << endl;
	if (file.is_open()) {
		file.close();
	}
	if(glIsShader(handle) == GL_TRUE) {
		glDeleteShader(handle);
	}
}
